#include "sle_low_latency.h" //包含了低延迟通信相关的头文件
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include "cmsis_os2.h"
#include "app_init.h"
#include "soc_osal.h" //包含了操作系统适配层相关的头文件

#include "common_def.h" //包含了通用定义相关的头文件
#include "pinctrl.h"
#include "uart.h"

#include "securec.h"
#include "sle_device_discovery.h"
#include "sle_errcode.h" //包含了错误代码相关的头文件

#include "lwip/nettool/misc.h" //包含了网络工具相关的头文件
#include "lwip/ip4_addr.h"
#include "lwip/netif.h"
#include "lwip/netifapi.h"
#include "lwip/sockets.h"

#include "watchdog.h"
#include "i2c.h"
#include "osal_debug.h" //包含了调试相关的头文件

#include "gpio.h"
#include "sle_connection_manager.h"
#include "sle_ssap_client.h"
#include "sle_uart_client.h"
// #include "sht3x.h"
#include "mydevice/mydevice.h"
// #include "module/sle/sle_one/sle_one.h"
#define SLE_UART_TASK_STACK_SIZE            0x600 //定义了UART任务栈大小
//全局变量
SensorData othData = { //定义了一个全局的传感器数据结构体变量
    .ligBuffer = "",  // 初始化为空字符串
    .humidity = "",
    .temperature = "",
    .soilHum = "",
    .id = 0
};

char send_data[100]={0}; //定义了一个字符数组，用于存储发送的数据
#define UART_TASK_PRIO                     (osPriority_t)(17)
#define SLE_UART_TASK_PRIO                  28 //定义了UART任务的优先级
#define CONFIG_UART_INT_WAIT_MS            5 //定义了UART中断等待时间
#define UART_TASK_DURATION_MS              1000 //定义了UART任务的持续时间

static uint8_t g_app_uart_int_rx_flag = 0; //定义了一个标志位，用于指示UART接收中断

static uint8_t lora_rx_buff[UART_TRANSFER_SIZE] = { 0 }; //定义了一个用于存储LoRa接收数据的缓冲区

static uart_buffer_config_t lora_buffer_config = { //定义了一个UART缓冲区配置结构体
    .rx_buffer = lora_rx_buff, //设置接收缓冲区为之前定义的lora_rx_buff
    .rx_buffer_size = UART_TRANSFER_SIZE //设置接收缓冲区大小
};
// 设备信息结构体
typedef struct {
    uint16_t conn_id;        // 连接ID
    bool active;             // 是否活跃
} DeviceInfo;

static DeviceInfo devices[MAX_DEVICES];  // 设备列表
static uint8_t device_count = 0;         // 当前设备数量
// 根据数据解析是否为"getid"指令
static bool is_getid_command(const char *data) {
    return (data && strncmp(data, "getid", 5) == 0);
}
// 查找设备索引
static int find_device_index(uint16_t conn_id) {
    for (int i = 0; i < device_count; i++) {
        if (devices[i].conn_id == conn_id) {
            return i;
        }
    }
    return -1;
}

// 添加或更新设备信息
static void add_or_update_device(uint16_t conn_id) {
    int index = find_device_index(conn_id);
    
    if (index < 0) {
        // 新设备
        if (device_count < MAX_DEVICES) {
            devices[device_count].conn_id = conn_id;
            devices[device_count].active = true;

            device_count++;
            osal_printk("New device added: conn_id=%d\r\n", conn_id);
        } else {
            osal_printk("Error: Too many devices (max %d)\r\n", MAX_DEVICES);
        }
    } else {
        // 更新现有设备
        devices[index].active = true;
    }
}

// 标记设备为不活跃
static void mark_device_inactive(uint16_t conn_id) {
    int index = find_device_index(conn_id);
    if (index >= 0) {
        devices[index].active = false;
    }
}

// 处理"getid"指令，返回"setid:ID,"格式响应
static void handle_getid_command(uint16_t conn_id) {

    // 构建响应数据
    char response[20] = {0};
    snprintf(response, sizeof(response), "setid:%d,", conn_id); // 假设只有一个主设备
    
    osal_printk("Sending setid response: %s\r\n", response);
    
    // 发送响应
    ssapc_write_param_t *send_param = get_g_sle_uart_send_param();
    send_param->data_len = strlen(response);
    send_param->data = (uint8_t *)response;
    
    ssapc_write_req(0, conn_id, send_param);
}

// 定义了一个处理LoRa通知数据的回调函数
void sle_uart_notification_cb(uint8_t client_id, uint16_t conn_id, ssapc_handle_value_t *data, errcode_t status) {
    unused(client_id); 
    // unused(conn_id); 
    unused(status); 

    osal_printk("\n sle uart re data : %s\r\n", data->data); 
    osal_printk("connid:%d\r\n",conn_id);

    // 添加或更新设备信息
    add_or_update_device(conn_id);

    uint8_t *buff = (uint8_t *)(data->data); 

    if (is_getid_command((const char*)buff)) {
        osal_printk("Received getid command\r\n");
        // 处理getid指令，发送setid响应
        handle_getid_command(conn_id); // 假设conn_id为0，可根据实际情况修改
        return; // 返回虚拟ID表示处理了getid指令
    }else{
        // 将接收到的数据通过UART发送出去
        uapi_uart_write(CONFIG_LORA_BUS, (uint8_t *)(data->data), data->data_len+2, 0); 
    }
    
    // 将接收到的数据拷贝到lora_rx_buff缓冲区中
    if (memcpy_s(lora_rx_buff, data->data_len, buff, data->data_len) != EOK) {
        osal_printk("uart%d int mode data copy fail!\r\n", CONFIG_LORA_BUS); 
        osal_printk("data:%s\r\n", buff); 
        return;
    }
}

//定义了一个处理LoRa指示数据的回调函数
void sle_uart_indication_cb(uint8_t client_id, uint16_t conn_id, ssapc_handle_value_t *data, errcode_t status) {
    unused(client_id); 
    unused(conn_id); 
    unused(status); 

    osal_printk("\n sle uart 收发 : %s\r\n", data->data); 
    uapi_uart_write(CONFIG_LORA_BUS, (uint8_t *)(data->data), data->data_len+1, 0); 
}

//定义了一个处理UART读操作的回调函数
static void sle_uart_client_read_int_handler(const void *buffer, uint16_t length, bool error) {
    unused(error); //表示error参数未被使用
    if (buffer == NULL || length == 0) {
        osal_printk("uart%d int mode transfer illegal data!\r\n", CONFIG_LORA_BUS);
        return;
    }

    uint8_t *buff = (uint8_t *)buffer; //将buffer转换为uint8_t指针类型
    char num_str[2] = { buff[0], '\0' }; //从接收到的数据中提取第一个字符作为连接ID

    ssapc_write_param_t *sle_uart_send_param = get_g_sle_uart_send_param(); //获取SLE UART发送参数
    uint16_t g_sle_uart_conn_id = atoi(num_str); //将提取的字符转换为整数作为连接ID

    osal_printk("\n sle_uart_client_read_int_handler: %d\r\n", g_sle_uart_conn_id); //打印连接ID
    osal_printk("\n data: %s\r\n", buff); //打印连接ID


    sle_uart_send_param->data_len = length - 1; //设置发送数据长度
    sle_uart_send_param->data = (uint8_t *)buffer + 1; //设置发送数据指针，跳过第一个字节（连接ID）

    ssapc_write_req(0, g_sle_uart_conn_id, sle_uart_send_param); //通过SLE协议发送数据
    // my_sle_uart_client_write(sle_uart_send_param->data, sle_uart_send_param->data_len);
}
// 发送数据请求
static void send_data_request(uint16_t conn_id) {
    const char *request = "getdata";
    
    osal_printk("Sending request to device %d: %s\r\n", conn_id, request);
    
    // 发送请求
    ssapc_write_param_t *send_param = get_g_sle_uart_send_param();
    send_param->data_len = strlen(request);
    send_param->data = (uint8_t *)request;
    
    ssapc_write_req(0, conn_id, send_param);
}

//定义了UART客户端任务的入口函数
static void *sle_uart_client_task(const char *arg) {
    unused(arg); //表示arg参数未被使用

    //初始化SLE UART客户端
    sle_uart_client_init(sle_uart_notification_cb, sle_uart_indication_cb);
    // 定义并初始化当前设备索引
    static uint8_t current_device_idx = 0;
    while (1) {
        // 每次循环处理一个设备，避免内层循环延时
        if (device_count > 0) {
            current_device_idx = (current_device_idx + 1) % device_count;
            if (devices[current_device_idx].active) {
                send_data_request(devices[current_device_idx].conn_id);
            }
        }
        osDelay(5000); // 统一延时，简化逻辑
    }
    
    
    return NULL;
}

// //定义了UART模块的入口函数
// stat

//     //释放任务调度锁
//     osal_kthread_unlock();
// }

//注册UART模块的入口函数
// app_run(sle_uart_entry);
static void *uart_task(const char *arg)
{
    unused(arg);
    //初始化UART GPIO引脚
    uart_gpio_init(CONFIG_LORA_BUS, CONFIG_LORA_TXD_PIN, CONFIG_LORA_RXD_PIN);
    //初始化UART配置
    uart_init_config(CONFIG_LORA_BUS, CONFIG_LORA_TXD_PIN, CONFIG_LORA_RXD_PIN, &lora_buffer_config);

    //注销UART接收回调函数
    uapi_uart_unregister_rx_callback(CONFIG_LORA_BUS);
    uapi_uart_register_rx_callback(CONFIG_LORA_BUS, UART_RX_CONDITION_FULL_OR_IDLE, 1, sle_uart_client_read_int_handler);

    return NULL;
}
static void uart_entry(void)
{
    osal_task *task_handle = NULL;
    osal_task *task_handle1 = NULL;

    osal_kthread_lock();
    task_handle = osal_kthread_create((osal_kthread_handler)uart_task, 0, "UartTask", 0x1000);
    if (task_handle != NULL) {
        osal_kthread_set_priority(task_handle, UART_TASK_PRIO);
        osal_kfree(task_handle);
    }

    //创建UART客户端任务
    task_handle1 = osal_kthread_create((osal_kthread_handler)sle_uart_client_task, 0, "SLEUartDongleTask", SLE_UART_TASK_STACK_SIZE);

    //如果任务创建成功，设置任务优先级
    if (task_handle1 != NULL) {
        osal_kthread_set_priority(task_handle1, SLE_UART_TASK_PRIO);
    }
    osal_kthread_unlock();
}

/* Run the uart_entry. */
app_run(uart_entry);